package com.jindy.module.machine.service.impl;

import java.util.ArrayList;
import java.util.List;
import com.jindy.module.constant.StatusConstants;
import com.jindy.module.machine.domain.Machine;
import com.jindy.module.machine.domain.MachineRecord;
import com.jindy.module.machine.mapper.MachineMapper;
import com.jindy.module.machine.mapper.MachineRecordMapper;
import com.jindy.module.machine.service.IMachineService;
import com.jindy.module.order.domain.Order;
import com.jindy.module.order.mapper.OrderMapper;
import com.jindy.module.stock.domain.Stock;
import com.jindy.module.stock.mapper.StockMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 机器Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-14
 */
@Service
public class MachineServiceImpl implements IMachineService
{
    @Resource
    private MachineMapper machineMapper;

    @Resource
    private StockMapper stockMapper;

    @Resource
    private MachineRecordMapper machineRecordMapper;

    @Resource
    private OrderMapper orderMapper;

    /**
     * 查询机器
     *
     * @param id 机器主键
     * @return 机器
     */
    @Override
    public Machine selectMachineById(String id)
    {
        return machineMapper.selectMachineById(id);
    }

    /**
     * 查询机器列表
     *
     * @param machine 机器
     * @return 机器
     */
    @Override
    public List<Machine> selectMachineList(Machine machine)
    {
        return machineMapper.selectMachineList(machine);
    }

    /**
     * 新增机器
     *
     * @param machine 机器
     * @return 结果
     */
    @Override
    public int insertMachine(Machine machine)
    {
        return machineMapper.insertMachine(machine);
    }

    /**
     * 修改机器
     *
     * @param machine 机器
     * @return 结果
     */
    @Override
    public int updateMachine(Machine machine)
    {
        return machineMapper.updateMachine(machine);
    }

    /**
     * 修改机器状态时改变可用库存
     *
     * @param machine 机器
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMachine1(Machine machine)
    {
        //找到此时的机器
        Machine machine1 = machineMapper.selectMachineById(machine.getId());
        //如果此时传入状态是正常（0），而此时机器状态为不可用（1），表示机器可以正常使用了，可用库存数量+1
        if(machine.getStatus().equals("0") && machine1.getStatus().equals("1")){
            Stock stock = new Stock();
            stock.setModel(machine.getModel());
            stock.setWarehouseId(machine.getWarehouseId());
            List<Stock> stockList = stockMapper.selectStockList(stock);
            if(!CollectionUtils.isEmpty(stockList)){
                Stock stock1 = stockList.get(0);
                stock1.setAvailableQuantity(stock1.getAvailableQuantity()+1);
                stockMapper.updateStock(stock1);
            }
        }
//        int result = machineMapper.updateMachine(machine);
        return machineMapper.updateMachine(machine);
    }

    /**
     * 机器修好后，根据前端传入的机器状态，判断是否改变库存
     *
     * @param machine 机器
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMachine2(Machine machine) {
        int result = 0;
        //        if(machine.getStatus() != null &&!machine.getStatus().isEmpty()){}
        Machine machine1 = machineMapper.selectMachineById(machine.getId());
        //这是一台之前报修的机器
        if ("1".equals(machine1.getStatus())) {
            String status = machine.getStatus();
            if (status != null && !status.isEmpty()) {
                if ("0".equals(status)) {//这是回库后报修的机器，该仓库可用数量加一，状态改为正常
                    // 4:修改仓库库存
                    Stock stock = new Stock();
                    stock.setProductId(machine1.getProductId());
                    stock.setModel(machine1.getModel());
                    stock.setWarehouseId(machine1.getWarehouseId());
                    List<Stock> stocks = stockMapper.selectStockList(stock);
                    //库存数量+1
                    if (!CollectionUtils.isEmpty(stocks)) {
                        stock = stocks.get(0);
                        stock.setAvailableQuantity(stock.getAvailableQuantity() + 1);
                        stockMapper.updateStock(stock);
                    }
                } else if ("2".equals(status)) {//这是项目上报修的机器，可用数量不变，状态改为正常
                    machine.setStatus(StatusConstants.MachineStatusConstant.machineStatus_2);
                } else {//其他状态的机器抛出异常
                    throw new RuntimeException("机器状态校验失败，请重新选择");
                }
                result = machineMapper.updateMachine(machine);
            }else {//机器状态不能为空
                throw new RuntimeException("机器状态不能为空！");
            }
        }else {//这台机器不是报修机器
            throw new RuntimeException("这台机器不是报修机器，请重新扫码！");
        }
        return result;
    }




    /**
     * 机器修好后，修改机器状态时判断是否改变可用库存
     *
     * @param machine 机器
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMachine3(Machine machine) {
        int result = 0;
        //找到此时的机器
        Machine machine1 = machineMapper.selectMachineById(machine.getId());
        if ("1".equals(machine1.getStatus())) {
            List<Order> orderList = new ArrayList<>();
            List<Order> orderList2 = new ArrayList<>();
            //通过传入的机器编号筛选出对应的订单（尚未入库，或入库申请中）
            MachineRecord machineRecord = new MachineRecord();
            machineRecord.setMachineNo(machine1.getMachineNo());
            List<MachineRecord> machineRecordList = machineRecordMapper.selectMachineRecordList(machineRecord);
            machineRecordList.forEach(machineRecord1 -> {
                if (machineRecord1.getOutboundTime() != null) {
                    Order order1 = orderMapper.selectOrderById(machineRecord1.getOrderId());
                    if (order1 != null) {
                        if ("4".equals(order1.getOrderStatus()) || "5".equals(order1.getOrderStatus())) {
                            orderList.add(order1);
                        } else if ("6".equals(order1.getOrderStatus())) {
                            orderList.add(order1);
                        } else {
                            orderList2.add(order1);
                        }
                    }
                }
            });
            if (orderList2.size() == 0) {//这是回库后报修的机器，该仓库可用数量加一，状态改为正常

                // 4:修改仓库库存
                Stock stock = new Stock();
                stock.setProductId(machine1.getProductId());
                stock.setModel(machine1.getModel());
                stock.setWarehouseId(machine1.getWarehouseId());
                List<Stock> stocks = stockMapper.selectStockList(stock);
                //如果机器所入的仓库有这个类型的机器，则库存数量+1
                if (!CollectionUtils.isEmpty(stocks)) {
                    stock = stocks.get(0);
                    stock.setAvailableQuantity(stock.getAvailableQuantity() + 1);
                    stockMapper.updateStock(stock);
                }
                //修改机器为正常
                machine.setStatus(StatusConstants.MachineStatusConstant.machineStatus_0);
            } else {//这是项目上报修的机器，数量不变状态改为正常
                machine.setStatus(StatusConstants.MachineStatusConstant.machineStatus_2);
            }
            result = machineMapper.updateMachine(machine);
        }
        return result;
    }



    /**
     * 批量删除机器
     *
     * @param ids 需要删除的机器主键
     * @return 结果
     *//*
    @Override
    public int deleteMachineByIds(Long[] ids)
    {
        return machineMapper.deleteMachineByIds(ids);
    }*/

    /**
     * 删除机器信息
     *
     * @param id 机器主键
     * @return 结果
     *//*
    @Override
    public int deleteMachineById(Long id)
    {
        return machineMapper.deleteMachineById(id);
    }*/
}
